package com.itheima.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;

@RestController
@RequestMapping("/user")
public class UserController {

    @Reference
    private UserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 查询登录的会员名
     * @return
     */
    @RequestMapping("findUserName")
    public Result findUserName() {

        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (user != null) {
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS, user.getUsername());
        }
        return new Result(false, MessageConstant.GET_USERNAME_FAIL);
    }

    /**
     * 分页查询会员列表
     * @param queryPageBean
     * @return
     */
    @RequestMapping("findByPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        PageResult pageResult = userService.findPage(queryPageBean);
        return pageResult;
    }

    /**
     * 添加会员
     * @param user
     * @return
     */
    @RequestMapping("add")
    public Result add(@RequestBody com.itheima.domain.User user) {
        try {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
            userService.add(user);
            return new Result(true, MessageConstant.ADD_USER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_USER_FALL);
        }
    }

    /**
     * 修改会员的角色
     * @param id
     * @param ids
     * @return
     */
    @RequestMapping("updateRole")
    public Result updateRole(Integer id, @RequestBody Integer[] ids) {
        try {
            userService.updateRole(id, ids);
            return new Result(true, "修改用户角色成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "修改用户角色失败");
        }
    }

}
